<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <button>点击解析search参数</button>
    <div class="box"></div>
    <script>
      var btn = document.querySelector("button");
      var boxEle = document.querySelector(".box");
      // window.location.search = "?name=wqz&age=25&height=168cm";
      btn.onclick = function () {
        var str = window.location.search; //search返回值是数组"?name=wqz&age=25&height=168cm"
        var obj = formatSearch(str);
        var htmlStr = `<p>姓名:${obj.name}年龄:${obj.age}身高:${obj.height}</p>`;
        boxEle.innerHTML = htmlStr;
      };
      function formatSearch(str) {
        str = str.substr(1); //第一个参数是？ 从这里切掉
        var arr = str.split("&"); //数组是["name=wqz","age=25","height=168cm"]
        var obj = {};
        arr.forEach(function (item) {
          var newarr = item.split("="); //spilt将字符串切割成数组 "name=wqz"->["name","wqz"]
          obj[newarr[0]] = newarr[1];
        });
        return obj;
      }
    </script>
  </body>
</html>
